import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Scheme} from '../entity/scheme.model';
import {Http, Headers} from '@angular/http';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class SchemeService {
  private readonly param = 'schemes';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  /**
   * 获得配置方案
   *
   * @memberof SchemeService
   */
  getSchemes(): Promise<Scheme[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Scheme[])
      .catch(this.handleError);
  }

  getSchemesBymModelIdCategoryId(modelId: number, categoryId: number): Promise<Scheme> {

    return this.http.get(`${this.url}/modelId/${modelId}/categoryId/${categoryId}`)
      .toPromise()
      .then(response => response.data as Scheme)
      .catch(this.handleError);
  }

  /**
   * 根据配置方案分类ID获得配置方案
   *
   * @memberof SchemeService
   */
  getSchemesByCategoryId(categoryId: number): Promise<Scheme[]> {
    return this.http.get(`${this.url}/categoryId/${categoryId}`)
      .toPromise()
      .then(response => response.data as Scheme[])
      .catch(this.handleError);
  }

  create(scheme: Scheme): Promise<Scheme> {
    return this.http
      .post(this.url, JSON.stringify(scheme))
      .toPromise()
      .then(res => res.data)
      .catch(this.handleError);
  }

  update(scheme: Scheme): Promise<boolean> {
    const url = `${this.url}`;
    return this.http
      .put(url, JSON.stringify(scheme))
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(keyIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    // const apiUrl = `http://192.168.15.150:8585/webapi/v1/schemes?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return result;
            case '-1':
              throw new Error(result.message);
            case '8001':
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  // hasSchemeService(schemeName: string,categoryId:number, schemeId: number) {
  //   let reg = /\//g;
  //   if (reg.test(schemeName)) {
  //     schemeName = schemeName.replace(reg,"%2F");
  //   }
  //   // const url = `${this.url}/schemeName/${schemeName}/categoryId/${categoryId}/schemeId/${schemeId}`;
  //   // const url = `http://192.168.15.3:8585/webapi/v1/schemes/schemeName/${schemeName}/categoryId/${categoryId}/schemeId/${schemeId}`;
  //   const url = `http://192.168.15.3:8585/webapi/v1/schemes/getBasicSchemeBySchemeName`;
  //   return this.http.get(url).map(response => {
  //     let code = response.code;
  //     switch (code) {
  //       case "3001":
  //         return true;
  //       case "3002":
  //         return false;
  //     }
  //   }).catch(this.handleError);
  // }

  hasSchemeService(schemeName: string, categoryId: number, schemeId: number) {
    let reg = /\//g;
    if (reg.test(schemeName)) {
      schemeName = schemeName.replace(reg, '%2F');
    }
    const url = `${this.url}/getBasicSchemeBySchemeName`;
    // const url = `http://192.168.15.3:8585/webapi/v1/schemes/getBasicSchemeBySchemeName`;
    return this.http.post(url, JSON.stringify({schemeName, categoryId, schemeId})).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

}


// WEBPACK FOOTER //
// ./src/app/service/scheme.service.ts
